<?php

namespace App\Http\Controllers\Admin;

use App\Models\CompetiteActivityEbook;
use App\Models\CompetiteActivityWorks;
use App\Models\CompetiteActivityWorksDatabase;
use App\Models\CompetiteActivityWorksEbook;
use App\Validate\CompetiteActivityEbookValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品电子书
 */
class CompetiteActivityEbookController extends CommonController
{

    public $score_type = 7;
    public $model = null;
    public $competiteActivityWorks = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new CompetiteActivityEbook();
        $this->competiteActivityWorks = new CompetiteActivityWorks();
        $this->validate = new CompetiteActivityEbookValidate();
    }



    /**
     * 列表
     * @param database_id 数据库id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param is_play int 是否发布 1 发布  2 未发布
     * @param keywords string 搜索关键词(作品电子书名称)
     * @param start_time datetime 创建时间(开始)
     * @param end_time datetime 创建时间(截止)
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_play = $this->request->is_play;
        $database_id = $this->request->database_id;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        $res = $this->model->lists($database_id, $keywords, $is_play, $start_time, $end_time, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $competiteActivityWorksEbookModel = new CompetiteActivityWorksEbook();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['intro'] = strip_tags($val['intro']);
            $res['data'][$key]['ebook_number'] = $competiteActivityWorksEbookModel->ebookNumber($val['id']);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", "YES", $res);
    }

    /**
     * 详情
     * @param id int 电子书id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        return $this->returnApi(200, "获取成功", true, $res);
    }



    /** 
     * 新增
     * @param database_id 数据库id
     * @param name int 电子书名称
     * @param author int 作者名称
     * @param img int 电子书封面图片
     * @param intro int 电子书简介
     * 
     * @param works_ids int 作品id 多个逗号拼接  一次最多选30个
     * @param ebook_img int 电子书图片 多个 | 拼接
     * @param pdf_address int 电子书pdf 一次只能上传一个
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        // $findWhere[] = ['database_id', '=', $this->request->database_id];
        // $is_exists = $this->model->nameIsExists($this->request->name, 'name', null, 1, $findWhere);

        // if ($is_exists) {
        //     return $this->returnApi(202, "该电子书名称已存在");
        // }

        // 启动事务
        DB::beginTransaction();
        try {
            $data = $this->request->all();
            unset($data['database_id']);
            unset($data['works_ids']);
            unset($data['ebook_img']);
            unset($data['pdf_address']);
            $this->model->add($data);
            //添加入电子书与数据量关联表
            $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
            $competiteActivityWorksDatabaseModel->add([
                'database_id' => $this->request->database_id,
                'ebook_id' => $this->model->id,
                'type' => 2,
            ]);

            //添加作品的时候可以附带添加商品
            $competiteActivityWorksEbookModel = new CompetiteActivityWorksEbook();
            $data['ebook_id'] = $this->model->id;
            if ($this->request->works_ids) {
                $data['works_ids'] = $this->request->works_ids;
                $competiteActivityWorksEbookModel->recordAdd($data);
            }
            if ($this->request->ebook_img) {
                $data['ebook_img'] = $this->request->ebook_img;
                $competiteActivityWorksEbookModel->recordAddImg($data);
            }
            if ($this->request->pdf_address) {
                $data['pdf_address'] = $this->request->pdf_address;
                $competiteActivityWorksEbookModel->recordAddPdf($data);
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            //   var_dump($e->getMessage());exit;
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "新增失败" . $e->getMessage().$e->getFile().$e->getLine());
        }
    }

    /**
     * 编辑
     * @param id int 电子书id 
     * @param database_id 数据库id
     * @param name int 电子书名称
     * @param author int 作者名称
     * @param img int 电子书图片
     * @param intro int 电子书简介
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        // $findWhere[] = ['database_id', '=', $this->request->database_id];
        // $is_exists = $this->model->nameIsExists($this->request->name, 'name', $this->request->id, 1, $findWhere);

        // if ($is_exists) {
        //     return $this->returnApi(202, "该电子书名称已存在");
        // }
        // 启动事务
        DB::beginTransaction();
        try {
            $data = $this->request->all();
            unset($data['database_id']);
            $this->model->change($data);
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            // dd($e->getMessage());
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 电子书id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        // 启动事务
        DB::beginTransaction();
        try {
            //删除电子书与数据量关联表
            $competiteActivityWorksDatabaseModel = new CompetiteActivityWorksDatabase();
            $competiteActivityWorksDatabaseModel->where('ebook_id', $this->request->id)->delete();

            //删除数据
            $this->model->del($this->request->id);

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "删除成功", true);
        } catch (\Exception $e) {
            // dd($e->getMessage());
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 发布与取消发布
     * @param ids 书籍id，多个用逗号拼接   all 是，其余字符  ids 必传
     * @param is_play 是否发布  1.发布  2.未发布  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

        $is_play = $this->request->is_play == 1 ? '发布' : '取消发布';
        if ($code === 200) {
            return $this->returnApi(200, $is_play . $msg, true);
        }
        return $this->returnApi($code, $is_play . $msg);
    }

    /**
     * 排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最大
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);

        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
